package lixp.jwt.config;

import lixp.err.MyException;
import lixp.jwt.utils.Imp.JwtUtilForJJwt;
import lixp.res.ResultEnum;
import lixp.res.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JwtInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Autowired
    JwtUtilForJJwt jwtUtilForJJwt;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws MyException {
       logger.info("开始校验token");
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(JwtToken.class)) {
            JwtToken jwtToken = method.getAnnotation(JwtToken.class);
            if (jwtToken.required()) {
                // 执行认证
                if (token == null) {
//                    throw new RuntimeException("无token，请重新登录");
                    throw new MyException(ResultUtil.error(ResultEnum.Token_NOT_FOUND));

//                    return false;
                }
//                logger.warn(token);
                // 获取 token 中的 userId

                Integer userId = jwtUtilForJJwt.getUserIdFromToken(token);
                logger.info("用户id:" + userId);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("afterCompletion");
    }
}
